package com.yyc.tool.conf;

import com.yyc.tool.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;

import static com.yyc.tool.conf.SecurityConstants.ignoreResources;

/**
 * @author: yyc
 * @Date: 2020/4/27 0027
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 配置url安全拦截配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .and()
                .csrf().disable()
                .addFilterBefore(filter, CsrfFilter.class).userDetailsService(userService);
        //.exceptionHandling().accessDeniedHandler(authenticationEntryPoint).authenticationEntryPoint(authenticationEntryPoint);
    }

    /**
     * 定义需要忽略的 资源配置
     * @param web webSecurity
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(ignoreResources);
    }

    /**
     * AuthenticationManager 为认证管理接口类，其定义了认证方法 authenticate()。
     * 四个实现类：
     *  1. ProviderManager 为认证管理类，实现了接口 AuthenticationManager ，并在认证方法
     *  2. authenticate() 中将身份认证委托给具有认证资格的 AuthenticationProvider 进行身份认证。
     * @return 认证器
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
